package com.wuhao.shootclient.base;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import butterknife.ButterKnife;

/**
 * 指纹验证 提示框
 * Created by lip on 2017/5/5.
 */

public abstract class BaseDialogFragment extends DialogFragment {

    private View mView;

    protected abstract int getLayout();

    protected void init() {

    }

    @Override
    public View getView() {
        if (mView != null) {
            return mView;
        }
        return null;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        getDialog().setCanceledOnTouchOutside(false); // 外部点击取消
        mView = inflater.inflate(getLayout(), container);
        ButterKnife.bind(this, mView);
        init();
        return mView;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (getDialog() != null && getDialog().getWindow() != null) {
            Window window = getDialog().getWindow();
            WindowManager.LayoutParams windowParams = window.getAttributes();
            windowParams.dimAmount = 0.0f;
            window.setAttributes(windowParams);
        }
    }

    public void show(FragmentActivity activity) {
        if (activity != null && !activity.isFinishing()) {
            show(activity.getSupportFragmentManager(), null);
        }
    }

    public void show(Fragment fragment) {
        if (fragment != null && !fragment.getActivity().isFinishing()) {
            show(fragment.getChildFragmentManager(), null);
        }
    }

    public void disMiss() {
        try {
            dismissAllowingStateLoss();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        if (isVisible() || isRemoving() || isAdded()) {
            return;
        }
        try {
            //在每个add事务前增加一个remove事务，防止连续的add
            manager.beginTransaction().remove(this).commitAllowingStateLoss();
            super.show(manager, tag);
        } catch (Exception e) {
            //同一实例使用不同的tag会异常,这里捕获一下
            e.printStackTrace();
            FragmentTransaction ft = manager.beginTransaction();
            ft.add(this, null);
            ft.commitAllowingStateLoss();
        }
    }


}
